using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Park.Net.EFCoreEnv;
using Park.Net.IRepository;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Park.Net.Repository
{
    public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class, new()
    {
      protected ParkDbContext ParkDb;

    // 构造函数，依赖注入 DbContext 对象
    public BaseRepository(ParkDbContext db)
    {
        this.ParkDb = db;
    }

    public async Task<bool> CreateAsync(TEntity entity)
    {
        await ParkDb.Set<TEntity>().AddAsync(entity);
        return await ParkDb.SaveChangesAsync() > 0;
    }

    public async Task<bool> DeleteAsync(TEntity entity)
    {
        ParkDb.Set<TEntity>().Remove(entity);
        return await ParkDb.SaveChangesAsync() > 0;
    }

    public virtual async Task<List<TEntity>> FindAllAsync()
    {
        return await ParkDb.Set<TEntity>().ToListAsync();
    }

    public virtual async Task<List<TEntity>> FindManyAsync(Expression<Func<TEntity, bool>> exp)
    {
        return await ParkDb.Set<TEntity>().Where(exp).ToListAsync();
    }

    public virtual async Task<TEntity> FindOneAsync(int id)
    {
        return await ParkDb.Set<TEntity>().FindAsync(id);
    }

    public virtual async Task<TEntity> FindOneAsync(Expression <Func<TEntity, bool>> exp)
    {
        return await ParkDb.Set<TEntity>().FirstOrDefaultAsync(exp);
    }

    public virtual async Task<bool> UpdateAsync(TEntity entity)
    {
        ParkDb.Set<TEntity>().Update(entity);
        return await ParkDb.SaveChangesAsync() > 0;
    }
    }
}
    
